﻿using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;

namespace PLC.PLCAlarm
{
    /// <summary>
    /// 报警信息管理器
    /// </summary>
    public class AlarmManager
    {
        private readonly ConcurrentDictionary<string, AlarmEntry> activeAlarms = new ConcurrentDictionary<string, AlarmEntry>();

        /// <summary>
        /// 添加报警
        /// </summary>
        /// <param name="e"></param>
        public void AddAlarm(RecordAlarmDataArgs e)
        {
            var alarmInfo = new AlarmEntry
            {
                AlarmCode = e.AlarmCode,
                AlarmInfo = e.AlarmInfo,
                AlarmDate = e.AlarmDate,
                StartTime = e.StartTime
            };

            activeAlarms.TryAdd(e.AlarmCode, alarmInfo);
        }
        /// <summary>
        /// 删除报警
        /// </summary>
        /// <param name="e"></param>
        public void RemoveAlarm(RecordAlarmDataArgs e)
        {
            activeAlarms.TryRemove(e.AlarmCode, out _);
        }
        /// <summary>
        /// 获取报警文本
        /// </summary>
        /// <returns></returns>
        public string GetFormattedAlarmText()
        {
            var sb = new StringBuilder();
            foreach (var alarm in activeAlarms.Values.OrderByDescending(a => a.StartTime))
            {
                sb.AppendLine($"报警: 代码 {alarm.AlarmCode}, 内容 {alarm.AlarmInfo}, 日期 {alarm.AlarmDate}, 开始时间 {alarm.StartTime:HH:mm:ss}");
            }
            return sb.ToString().TrimEnd();
        }

        /// <summary>
        /// 获取报警JOSN
        /// </summary>
        /// <returns></returns>
        public string GetActiveAlarmsJson()
        {
            return JsonConvert.SerializeObject(activeAlarms.Values);
        }
    }

    /// <summary>
    /// 报警类
    /// </summary>
    public class AlarmEntry
    {
        /// <summary>
        /// 报警代码
        /// </summary>
        public string AlarmCode { get; set; }
        /// <summary>
        /// 报警信息
        /// </summary>
        public string AlarmInfo { get; set; }
        /// <summary>
        /// 报警时间
        /// </summary>
        public string AlarmDate { get; set; }
        /// <summary>
        /// 报警开始时间
        /// </summary>
        public DateTime StartTime { get; set; }
    }
}
